package com.ebeitech.doorapp.qqim.util;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.view.View;

import com.ebeitech.doorapp.R;
import com.ebeitech.doorapp.application.EbeiApplication;
import com.ebeitech.doorapp.constants.CommonConstants;
import com.ebeitech.doorapp.util.PublicUtil;
import com.ebeitech.library.constant.MessageConstants;
import com.ebeitech.library.constant.SPConstants;
import com.ebeitech.library.ui.dialog.CommonAlertDialogFragment;
import com.ebeitech.library.util.CommonUtil;
import com.ebeitech.library.util.Log;
import com.ebeitech.library.util.SPManager;
import com.ebeitech.library.util.ViewUtil;
import com.tencent.imsdk.TIMCallBack;
import com.tencent.imsdk.TIMConnListener;
import com.tencent.imsdk.TIMManager;
import com.tencent.imsdk.TIMUserConfig;
import com.tencent.imsdk.TIMUserStatusListener;
import com.tencent.qcloud.presentation.business.LoginBusiness;
import com.tencent.qcloud.presentation.event.FriendshipEvent;
import com.tencent.qcloud.presentation.event.GroupEvent;
import com.tencent.qcloud.presentation.event.MessageEvent;
import com.tencent.qcloud.presentation.event.RefreshEvent;

import java.util.concurrent.TimeUnit;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by alice on 2017/11/3.
 */
public class QQIMUtil {

	public static final String TAG = "QQIMUtil";

	private Context context;

	private static QQIMUtil mQQIMUtil;

	private static int connectCount = 0;
	private static boolean isLoading = false;

	private Handler mHandler = new Handler(Looper.getMainLooper()) {
		public void handleMessage(android.os.Message msg) {
			if (msg != null) {
				int what = msg.what;
				Intent intent = new Intent(MessageConstants.ACTION_CONNECT_STATUS);
				intent.putExtra(MessageConstants.CONNECT_STATUS, what);
				context.sendBroadcast(intent);
			}
		}
	};

	public static QQIMUtil getInstance() {
		if (mQQIMUtil == null) {
			synchronized (QQIMUtil.class) {
				if (mQQIMUtil == null) {
					mQQIMUtil = new QQIMUtil();
				}
			}
		}
		return mQQIMUtil;
	}

	public void doLogin(final Context context, final String identifier) {
		this.context = context;
		String mUserAccount = SPManager.getInstance(context).get(SPConstants.USER_ACCOUNT, "");
		String loginUser = TIMManager.getInstance().getLoginUser();
		if (mUserAccount.equals(loginUser)) {
			Log.i("该用户已连接");
			return;
		}
		doLoginQQIM(context, identifier);
	}

	public void doLoginQQIM(final Context context, final String identifier) {
		if (isLoading) {
			return;
		}
		isLoading = true;
		if (!CommonUtil.isNetworkAvailable(context)) {
			isLoading = false;
			boolean isMessageConnect = SPManager.getInstance(context).get("isMessageConnect", false);
			if (isMessageConnect) {
				SPManager.getInstance(context).put("isMessageConnect", false);
				mHandler.sendEmptyMessage(MessageConstants.DISCONNECTED);
			}
			return;
		}

		Log.i("QQIM正在连接");
		String userSig = SPManager.getInstance(context).get(SPConstants.USER_SIG, "");
		TIMUserConfig userConfig = new TIMUserConfig();
		userConfig.setUserStatusListener(new TIMUserStatusListener() {
			@Override
			public void onForceOffline() {
				Log.d(TAG, "receive force offline message");
				// 被挤下线
				forceOffline();
			}

			@Override
			public void onUserSigExpired() {
				//票据过期，需要重新登录
				forceOffline();
			}
		}).setConnectionListener(new TIMConnListener() {
			@Override
			public void onConnected() {
				Log.i(TAG, "onConnected");
				doLoginQQIM(context,identifier);
			}

			@Override
			public void onDisconnected(int code, String desc) {
				Log.i(TAG, "onDisconnected");
				isLoading = false;
				SPManager.getInstance(context).put("isMessageConnect", false);
				mHandler.sendEmptyMessage(MessageConstants.DISCONNECTED);
			}

			@Override
			public void onWifiNeedAuth(String name) {
				Log.i(TAG, "onWifiNeedAuth");
			}
		});

		//设置刷新监听
		RefreshEvent.getInstance().init(userConfig);
		userConfig = FriendshipEvent.getInstance().init(userConfig);
		userConfig = GroupEvent.getInstance().init(userConfig);
		userConfig = MessageEvent.getInstance().init(userConfig);
		TIMManager.getInstance().setUserConfig(userConfig);

		mHandler.sendEmptyMessage(MessageConstants.CONNECTING);
		connectCount = 0;
		doLoginQQIM(context,identifier, userSig);
	}

	private void doLoginQQIM(final Context context, final String identifier , final String userSig) {
		connectCount++;
		LoginBusiness.loginIm(identifier, userSig, new TIMCallBack() {
			@Override
			public void onError(int i, String s) {
				Log.e(TAG, "login error : code " + i + " " + s);
				isLoading = false;
				SPManager.getInstance(context).put("isMessageConnect", false);
				mHandler.sendEmptyMessage(MessageConstants.DISCONNECTED);
				if (connectCount < 2) {
					Observable.just(1)
							.delay(5, TimeUnit.SECONDS)
							.subscribeOn(Schedulers.io())
							.observeOn(AndroidSchedulers.mainThread())
							.subscribe(new Subscriber<Integer>() {
								@Override
								public void onStart() {
									super.onStart();
									mHandler.sendEmptyMessage(MessageConstants.CONNECTED_AGAIN);
								}

								@Override
								public void onCompleted() {
									doLoginQQIM(context, identifier, userSig);
								}

								@Override
								public void onError(Throwable e) {

								}

								@Override
								public void onNext(Integer integer) {

								}
							});
				}
			}

			@Override
			public void onSuccess() {
				Log.i("该用户已连接");
				isLoading = false;
				connectCount = 0;
				SPManager.getInstance(context).put("isMessageConnect", true);
				mHandler.sendEmptyMessage(MessageConstants.CONNECTED);
				//初始化程序后台后消息推送
				PushUtil.getInstance();
				//初始化消息监听
				MessageEvent.getInstance();
			}
		});
	}

	public void doLogout() {
		Log.i("QQIM正在注销");
		TIMManager.getInstance().logout(new TIMCallBack() {
			@Override
			public void onError(int code, String desc) {

				//错误码code和错误描述desc，可用于定位请求失败原因
				//错误码code列表请参见错误码表
				android.util.Log.d("logout", "logout failed. code: " + code + " errmsg: " + desc);
			}

			@Override
			public void onSuccess() {
				//登出成功
			}
		});
	}

	private void forceOffline() {
		// 弹框前就调用腾讯的注销登录,防止长时间停留在这个页面
		SPManager.getInstance(context).put(CommonConstants.IS_LOGIN_OFFLINE, true);
		doLogout();
		// 弹框提醒
		final Context context = EbeiApplication.getContext();// 防止context不正确,DialogFragment报错
		CommonAlertDialogFragment dialog = ViewUtil.getAlertDialog(context, "", context.getString(R.string.login_with_another_client), new CommonAlertDialogFragment.OnBtnClickListener() {
			@Override
			public void onClick(View v, CommonAlertDialogFragment dialog) {
				ViewUtil.dismissDialog(dialog);
				PublicUtil.doLogout(context);
			}
		}, null, "", "");
		dialog.setCancelButtonVisible(false);

		if (EbeiApplication.isAppAlive()) {
			ViewUtil.showDialog(context, dialog);
		} else {
			SPManager.getInstance(context).put(CommonConstants.IS_LOGIN_OFFLINE_REMIND, false);
		}
	}

}
